package dk.modified.reshary;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

import dk.modified.reshary.GlobalState.TrackerName;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebviewActivity extends Activity {

	private WebView webview;

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_webview);
		Tracker t = ((GlobalState) getApplication())
				.getTracker(TrackerName.APP_TRACKER);
		t.setScreenName("Reshary Settings");
		t.send(new HitBuilders.AppViewBuilder().build());
		getActionBar().setDisplayHomeAsUpEnabled(true);
		Util.setActionBar(this,
				getResources().getString(R.string.title_activity_webview));
		String url = getIntent().getExtras().getString("url");

		webview = (WebView) findViewById(R.id.webview);
		webview.setWebViewClient(new myWebClient());
		webview.getSettings().setJavaScriptEnabled(true);
		webview.loadUrl(url);
		webview.setBackgroundColor(0x00000000);
		webview.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
	}

	public class myWebClient extends WebViewClient {
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// TODO Auto-generated method stub
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// TODO Auto-generated method stub

			view.loadUrl(url);
			return true;

		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onDestroy() {
		if (webview != null) {
			webview.removeAllViews();
			webview.destroy();
		}
		super.onDestroy();
	}

	@Override
	public void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		if (webview != null) {
			webview.destroy();
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (webview.canGoBack()) {
			webview.goBack();
			return;
		} else {
			finish();
			overridePendingTransition(R.anim.fadeout, R.anim.fadein);
		}

		super.onBackPressed();
	}

}
